<?php

use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Request;

if (!function_exists('admin_path')) {

    /**
     * Get admin path.
     *
     * @param string $path
     *
     * @return string
     */
    function admin_path($path = '')
    {
        return ucfirst(config('admin.directory')) . ($path ? DIRECTORY_SEPARATOR . $path : $path);
    }
}

if (!function_exists('admin_url')) {
    /**
     * Get admin url.
     *
     * @param string $url
     *
     * @return string
     */
    function admin_url($url = '')
    {
        $prefix = trim(config('admin.prefix'), '/');

        return url($prefix ? "/$prefix" : '') . '/' . trim($url, '/');
    }
}

if (!function_exists('admin_toastr')) {

    /**
     * Flash a toastr messaage bag to session.
     *
     * @param string $message
     * @param string $type
     * @param array $options
     *
     * @return string
     */
    function admin_toastr($message = '', $type = 'success', $options = [])
    {
        $toastr = new \Illuminate\Support\MessageBag(get_defined_vars());

        \Illuminate\Support\Facades\Session::flash('toastr', $toastr);
    }
}

function short_url_encode($url)
{
    $insert_data = [
        'url' => $url,
    ];
    $model = new \App\Models\ShortUrl();
    $created = $model->create($insert_data);
    return url('url/' . hashid_encode($created->id));
}

function short_url_decode($hash_id)
{
    $id = hashid_decode($hash_id);
    $model = new \App\Models\ShortUrl();
    $short = $model->find($id);
    return $short->url;
}

function getBarCode($code)
{
    $http = new \GuzzleHttp\Client(['base_uri' => config('custom.barcode_url'), 'timeout' => 2.0]);
    $response = $http->request('POST', '', [
        'form_params' => [
            'code' => $code
        ]
    ]);
    if ($response->getStatusCode() == 200) {
        return $response->getBody()->getContents();
    } else {
        return 'error';
    }
}

function urlHas($name)
{
    if (empty($name)) {
        return false;
    } else {
        if (strstr(url()->current(), $name)) {
            return true;
        }
    }

    return false;
}

function table($table)
{
    return 'store' . '_' . $table;
}

function object_array($array)
{
    if (is_object($array)) {
        $array = (array)$array;
    }
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            $array[$key] = object_array($value);
        }
    }
    return $array;
}


function array2object($array)
{
    if (is_array($array)) {
        $array = (object)$array;
    }
    if (is_object($array)) {
        $obj = new StdClass();
        foreach ($array as $key => $value) {
            $obj->$key = array2object($value);
        }
    } else {
        $obj = $array;
    }
    return $obj;
}

function ObjectToArray($array)
{
    if (is_object($array)) {
        $array = (array)$array;
    }
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            $array[$key] = object_array($value);
        }
    }
    return $array;
}

function ArrayToObject($array)
{
    if (is_array($array)) {
        $array = (object)$array;
    }
    if (is_object($array)) {
        $obj = new StdClass();
        foreach ($array as $key => $value) {
            $obj->$key = ArrayToObject($value);
        }
    } else {
        $obj = $array;
    }
    return $obj;
}

function object2array($object)
{
    if (is_object($object)) {
        foreach ($object as $key => $value) {
            $array[$key] = $value;
        }
    } else {
        $array = $object;
    }
    return $array;
}

function isWeChat()
{
    if (strpos(request()->server('HTTP_USER_AGENT'), 'MicroMessenger') == true && config('custom.wechat_share')) {
        return true;
    } else {
        return false;
    }
}


function userAgent()
{
    $userAgent = request()->server('HTTP_USER_AGENT');
    if (strpos($userAgent, 'MicroMessenger')) {
        return 'wechat';
    } else if (strpos($userAgent, 'ApliPayClient')) {
        return 'alipay';
    }
    return 'unknown';
}

function str_len($str)
{
    $length = strlen(preg_replace('/[\\x00-\\x7F]/', '', $str));

    if ($length) {
        return (strlen($str) - $length) + (intval($length / 3) * 2);
    } else {
        return strlen($str);
    }
}

if (!function_exists('price_format')) {
    function price_format($price, $change_price = true)
    {
        $currencyFormat = config('shop.currencyFormat');
        $priceFormat = config('shop.price_format');

        if ($price === '') {
            $price = 0;
        }

        if ($change_price) {
            switch ($priceFormat) {
                case 0:
                    $price = number_format($price, 2, '.', '');
                    break;

                case 1:
                    $price = preg_replace('/(.*)(\\.)([0-9]*?)0+$/', '\\1\\2\\3', number_format($price, 2, '.', ''));

                    if (substr($price, -1) == '.') {
                        $price = substr($price, 0, -1);
                    }

                    break;

                case 2:
                    $price = substr(number_format($price, 2, '.', ''), 0, -1);
                    break;

                case 3:
                    $price = intval($price);
                    break;

                case 4:
                    $price = number_format($price, 1, '.', '');
                    break;

                case 5:
                    $price = round($price);
                    break;
            }
        } else {
            @$price = number_format($price, 2, '.', '');
        }

        return sprintf($currencyFormat, $price);
    }
}

function get_sn()
{
    $time = explode(' ', microtime());
    $time = $time[1] . ($time[0] * 1000);
    $time = explode('.', $time);
    $time = (isset($time[1]) ? $time[1] : 0);
    $time = date('YmdHis') + $time;
    mt_srand((double)microtime() * 1000000);
    return $time . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
}

//function randomkeys($length)
//{
//    $pattern = '1234567890abcdefghijklmnopqrstuvwxyz';
//    $key = '';
//    for ($i = 0; $i < $length; $i++) {
//        $key .= $pattern{mt_rand(0, 35)};    //生成php随机数
//    }
//    return $key;
//}

/**
 *  将一个字串中含有全角的数字字符、字母、空格或'%+-()'字符转换为相应半角字符
 *
 * @access  public
 * @param string $str 待转换字串
 *
 * @return  string       $str         处理后字串
 */

function make_semiangle($str)

{

    $arr = array('０' => '0', '１' => '1', '２' => '2', '３' => '3', '４' => '4',
        '５' => '5', '６' => '6', '７' => '7', '８' => '8', '９' => '9',
        'Ａ' => 'A', 'Ｂ' => 'B', 'Ｃ' => 'C', 'Ｄ' => 'D', 'Ｅ' => 'E',
        'Ｆ' => 'F', 'Ｇ' => 'G', 'Ｈ' => 'H', 'Ｉ' => 'I', 'Ｊ' => 'J',
        'Ｋ' => 'K', 'Ｌ' => 'L', 'Ｍ' => 'M', 'Ｎ' => 'N', 'Ｏ' => 'O',
        'Ｐ' => 'P', 'Ｑ' => 'Q', 'Ｒ' => 'R', 'Ｓ' => 'S', 'Ｔ' => 'T',
        'Ｕ' => 'U', 'Ｖ' => 'V', 'Ｗ' => 'W', 'Ｘ' => 'X', 'Ｙ' => 'Y',
        'Ｚ' => 'Z', 'ａ' => 'a', 'ｂ' => 'b', 'ｃ' => 'c', 'ｄ' => 'd',
        'ｅ' => 'e', 'ｆ' => 'f', 'ｇ' => 'g', 'ｈ' => 'h', 'ｉ' => 'i',
        'ｊ' => 'j', 'ｋ' => 'k', 'ｌ' => 'l', 'ｍ' => 'm', 'ｎ' => 'n',
        'ｏ' => 'o', 'ｐ' => 'p', 'ｑ' => 'q', 'ｒ' => 'r', 'ｓ' => 's',
        'ｔ' => 't', 'ｕ' => 'u', 'ｖ' => 'v', 'ｗ' => 'w', 'ｘ' => 'x',
        'ｙ' => 'y', 'ｚ' => 'z',
        '（' => '(', '）' => ')', '〔' => '[', '〕' => ']', '【' => '[',
        '】' => ']', '〖' => '[', '〗' => ']', '“' => '[', '”' => ']',
        '‘' => '[', '’' => ']', '｛' => '{', '｝' => '}', '《' => '<',
        '》' => '>',
        '％' => '%', '＋' => '+', '—' => '-', '－' => '-', '～' => '-',
        '：' => ':', '。' => '.', '、' => ',', '，' => '.', '、' => '.',
        '；' => ',', '？' => '?', '！' => '!', '…' => '-', '‖' => '|',
        '”' => '"', '’' => '`', '‘' => '`', '｜' => '|', '〃' => '"',
        '　' => ' ');

    return strtr($str, $arr);

}

/**
 * 过滤用户输入的基本数据，防止script攻击
 *
 * @access      public
 * @return      string
 */
function compile_str($str)
{
    $arr = array('<' => '＜', '>' => '＞', '"' => '”', "'" => '’');

    return strtr($str, $arr);
}

function sub_str($str, $length = 0, $append = true)
{
    $str = trim($str);
    $strlength = strlen($str);
    if (($length == 0) || ($strlength <= $length)) {
        return $str;
    } else if ($length < 0) {
        $length = $strlength + $length;

        if ($length < 0) {
            $length = $strlength;
        }
    }

    if (function_exists('mb_substr')) {
        $newstr = mb_substr($str, 0, $length, CHARSET);
    } else if (function_exists('iconv_substr')) {
        $newstr = iconv_substr($str, 0, $length, CHARSET);
    } else {
        $newstr = substr($str, 0, $length);
    }

    if ($append && ($str != $newstr)) {
        $newstr .= '...';
    }

    return $newstr;
}

function order_fee($goods)
{
    $total = array(
        'real_goods_count' => 0,
        'goods_price' => 0,
        'market_price' => 0,
        'original_price' => 0,
        'count' => 0
    );
    foreach ($goods as $val) {
        $total['real_goods_count']++;
        $total['goods_price'] += $val['goods_price'] * $val['goods_number'];
        $total['market_price'] += $val['market_price'] * $val['goods_number'];
        $total['original_price'] += $val['original_price'] * $val['goods_number'];
        $total['count'] += $val['goods_number'];
    }
    $total['goods_price'] = floatval($total['goods_price']);
    $total['market_price'] = floatval($total['market_price']);
    return $total;
}

function seconds_time($seconds)
{
    $time = $seconds;
    $d = floor($time / (3600 * 24));
    $h = floor(($time % (3600 * 24)) / 3600);
    $m = floor((($time % (3600 * 24)) % 3600) / 60);
    if ($d > '0') {
        return ['day' => $d, 'hours' => $h, 'minute' => $m];
    } else {
        if ($h != '0') {
            return ['hours' => number_format($h), 'minute' => number_format($m)];
        } else {
            return ['minute' => $m];
        }
    }
}

/**
 * @param $array
 * @param $num
 * @return array
 */
function num_array($array, $num)
{
    $data = [];
    $item = [];
    $i = 0;
    foreach ($array as $key => $value) {
        $item[] = $value;
        if (count($item) - 1 == $num) {
            $i++;
            $data[$i] = $item;
            $item = [];
        } else {
            $data[$i] = $item;
        }
    }
    return $data;
}

;

function JsonToArray($data)
{
    $arr = [];
    foreach ($data as $k => $v) {
        $arr[] = $v;
    }
    return $arr;
}

/**
 * 随机的文件名
 * @param   $ext
 * @return string 随机字符串
 */
function randName($ext): string
{
    return md5(time() . mt_rand(1, 1000000)) . '.' . $ext;
}

/**
 * 文件上传
 * */
function upload($file, $file_path, $is_media = true): array
{
    $allow_type = ['gif', 'jpg', 'jpeg', 'png'];//图片格式，用来区分是否是图片上传(!勿动！)
    if (!$file->hasFile('file')) {
        exit('上传文件为空！');
    }
    $inputFile = $file->file('file');
    if (!$inputFile->isValid()) {
        exit('文件上传出错！');
    }

    $ext = \Illuminate\Support\Str::lower($inputFile->getClientOriginalExtension());
    $type = $inputFile->getMimeType();


    if ($ext && !in_array($ext, $allow_type)) {
        return ['return_code' => 'FAIL', 'message' => '不支持' . $type . '文件'];
    }

    $path = $inputFile->storeAs($file_path, randName($ext));

    if (empty($path)) {
        return ['return_code' => 'FAIL', 'message' => '文件出错'];
    }

//        /** 压缩图片 */
//        $img = ImageManager::make(Storage::path($path));
//        if ($img->width() > 400) {
//            $img->widen(400);
//            $img->save();
//        }
//        $img->destroy();

    if ($is_media) {
        $fileUrl = Storage::url($path);
        if ($fileUrl) {
            return [
                'url' => $fileUrl,
                'path' => $path,
                'uid' => randName($ext),
                'name' => randName($ext),
                'status' => 'done',
                'response' => ["status" => "success"],
            ];
        }
        return ['return_code' => 'FAIL', 'message' => '数据保存错误'];
    } else {
        return ['return_code' => 'SUCCESS', 'path' => $path];
    }
}

function get_file_url($path): string
{
    if (filter_var($path, FILTER_VALIDATE_URL) !== false) {
        return $path;
    }
    $storage = app('Storage');
    if (config('filesystems.default') === 'oss') {
        $fileUrl = $storage::exists($path) ? $storage::url($path) : config('app.url') . '/storage/' . $path;
    } else {
        $fileUrl = $storage::url($path);
    }
    return $fileUrl;
}







